//
//  OrderFinishView.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/11.
//

import SwiftUI

struct OrderFinishView: View {
    var carOrder : CarOrder = CarOrder.shared
    @Binding var showChatWindow : Bool
    @State var showNewMessageNotification = false
    @State private var opacity = 0.0
    
//    let url = URL(string: "https://picsum.photos/200/300")
    let laos_point = CarOrder.shared.read()
    
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading){
                Spacer()
                VStack(alignment: .leading,spacing: 10){
                    Text("已到达目的地")
                        .font(.system(size: 16))
                    Text("您已安全到达目的地，请带好您的随身物品下车")
                        .font(.system(size: 12))
                        .foregroundColor(Color.gray)
                    createRuningView()
                    createDestinationView()
                    
                }
                .padding(.horizontal,15)
                .padding(.vertical,15)
                .cornerRadius(10)
                .background(.linearGradient(Gradient(colors: [Color(hex: "#F8FFF8"),Color(hex: "#FCFBE4")]), startPoint: .leading, endPoint: .trailing))
                .clipShape(RoundedTopRectangle(cornerRadius: 20))
            }
            
            //            VStack {
            //                Spacer()
            //                VStack(alignment: .center) {
            //                    //          Rectangle().fill(Color(hex: "FF862F8D")).frame(width: 50,height:10)
            //                    HStack {
            //                        Image("call_car")
            //                            .resizable()
            //                            .frame(width: 60, height: 40)
            //                        Text("行程结束，您可以选择现金支付或者微信支付").foregroundColor(.black).font(.system(size: 18))
            //                        Spacer()
            //                    }
            ////                    Text("行程结束，您可以选择现金支付或者微信支付").foregroundColor(.black)
            //                    VStack() {
            //                        HStack(spacing: 50) {
            //                            VStack(alignment: .leading) {
            //                                Text("\(carOrder.carNo)").foregroundColor(.black).font(.system(size: 24, weight: .medium))
            //                                Rectangle().fill(Color(hex: "#F0CCFF")).frame(height:10)
            //                            }
            //                            Image("call_car_icon")
            //                                .resizable()
            //                                .frame(width: 125, height: 125)
            //
            //                        }
            //                        HStack {
            //                            Button {
            //                                print("open chat window...")
            //                                self.showChatWindow = true
            //                                self.showNewMessageNotification = false
            //                            } label: {
            //
            //                                VStack {
            //                                    Image("chat").resizable().frame(width: 30, height: 30)
            //                                    Text("聊天沟通").font(.system(size: 14)).padding(.top,-4).foregroundColor(.black).offset(y:2).frame(width: 80)
            //                                }
            //                            }
            //
            //                            Button {
            //                                print("call driver phone...")
            //                                guard let number = URL(string: "tel://" + carOrder.driverPhone) else { return }
            //                                UIApplication.shared.open(number)
            //                            } label: {
            //                                VStack {
            //                                    Image("service_phone").resizable().frame(width: 30, height: 30)
            //                                    Text("司机电话").font(.system(size: 14)).padding(.top,-2).foregroundColor(.black)
            //                                }
            //                            }
            //                        }.padding(.horizontal, 20)
            //                    }
            //                    .padding(.horizontal , 15)
            //                    .padding(.bottom, 10)
            //                    .background(.white)
            //                    .cornerRadius(16)
            //                    .shadow(radius: 0.1)
            //
            //                }
            //                .padding(20)
            //                .frame(width:geometry.size.width)
            //                .background(Color(hex: "#F1F4FA"))
            //                .cornerRadius(16)
            ////                .offset(x:10)
            //                .shadow(radius: 4)
            //            }
            
            
            .onReceive(NotificationCenter.default.publisher(for: .newMessage), perform: { _ in
                self.showNewMessageNotification = true
            })
        }
    }
}

//struct OrderFinishView_Previews: PreviewProvider {
//    static var previews: some View {
//        OrderFinishView(showChatWindow: .constant(true))
//    }
//}

extension OrderFinishView {
    
    func createRuningView() -> some View {
        VStack{
            HStack(){
                VStack(alignment: .leading){
                    Text("\(CarOrder.shared.carNo)")
                        .font(.system(size: 32,weight: .bold))
                    Text("品牌∙型号")
                        .font(.system(size: 14))
                }
                Spacer()
                ZStack{
                    Image("taxi_car")
                        .resizable()
                        .frame(width: 100,height: 80)
                    AsyncImage(url: URL(string: carOrder.headavitor.isEmpty ? "" : carOrder.headavitor) ) { phase in
                        switch phase {
                        case .empty:
                            ProgressView() // 加载中
                        case .success(let image):
                            image
                                .resizable()
                                .frame(width: 40,height: 40)
                        case .failure:
                            Image(systemName: "photo") // 加载失败
                                .resizable()
                                .frame(width: 40,height: 40)
                        @unknown default:
                            EmptyView()
                        }
                        
                    }
                    .clipShape(RoundedRectangle(cornerRadius: 20)) // 先裁剪圆角
                        .overlay(
                            RoundedRectangle(cornerRadius: 20)
                                .stroke(Color.white, lineWidth: 1) // 再添加边框
                        )

                    .offset(x: 40, y: -20)
                }
            }.padding(.horizontal,15)
                .padding(.vertical,15)
            Divider()
            HStack{
                Button {
                    guard let number = URL(string: "tel://" + carOrder.driverPhone) else { return }
                    UIApplication.shared.open(number)
                } label: {
                    Spacer()
                    Image("打电话") // 加载失败
                        .resizable()
                        .frame(width: 20,height: 20)
                    Text("打电话").foregroundColor(.black).font(.system(size: 12))
                    Spacer()
                }
                Divider()
                Button {
                    self.showChatWindow = true
                    self.showNewMessageNotification = false
                } label: {
                    Spacer()
                    ZStack {
                        Image("发信息") // 加载失败 car_runing_time@2x
                            .resizable()
                            .frame(width: 20,height: 20)
                        if self.showNewMessageNotification {
                            Image(systemName: "circle.fill")
                                .frame(width: 10, height: 10)
                                .offset(x: 15, y: -10)
                                .foregroundColor(.red)
                                .opacity(opacity)
                                .onAppear {
                                    withAnimation(.easeInOut(duration: 1.0)) {
                                        self.opacity = 1.0
                                    }
                                }
                                .onDisappear {
                                    withAnimation(.easeInOut(duration: 1.0)) {
                                        self.opacity = 0.0
                                    }
                                }
                        }
                    }
                 
                    Text("发信息").foregroundColor(.black).font(.system(size: 12))
                    Spacer()
                }
              
            }.frame(height:44)
        }.background(.white)
        .clipShape(RoundedRectangle(cornerRadius: 16)) // 先裁剪圆角
    }
    
    func createDestinationView() -> some View {
        VStack(alignment: .leading,spacing: 20){
            
            HStack(){
                Image("car_runing_time").resizable().frame(width: 20, height: 20)
                Text("\((Date(timeIntervalSince1970: TimeInterval(carOrder.startTime)).toStandardString))").foregroundColor(.black).font(.system(size: 12)).foregroundColor(.black).font(.system(size: 12))
                Spacer()
            }
            HStack(){
                Image("car_runing_sign")
                    .resizable()
                    .frame(width: 5, height: 40)
                VStack(alignment: .leading){
                    Text(carOrder.startLabel.isEmpty ? "上车位置".localized() : carOrder.startLabel).foregroundColor(.black).font(.system(size: 14))
                    Spacer()
                    Text(carOrder.endLabel.isEmpty ? "下车位置".localized() : carOrder.endLabel).foregroundColor(.black).font(.system(size: 14))
                    
                    
                }.frame(height: 50)
                
                Spacer()
            }
            Divider()
            HStack(){
                Text("已行驶距离").foregroundColor(.black).font(.system(size: 12))
                Spacer()
               
                Text("\( distanceKM(distance: laos_point?.mydistance ?? 0) ) \("公里".localized())").foregroundColor(.gray).font(.system(size: 12))
            }
            HStack(){
                Text("已行驶时间").foregroundColor(.black).font(.system(size: 12))
                Spacer()
                Text("\(laos_point?.mytime ?? 0) \("分钟".localized())").foregroundColor(.gray).font(.system(size: 12))
            }
            HStack(){
                Text("等待").foregroundColor(.black).font(.system(size: 12))
                Spacer()
                Text("\(laos_point?.waitTime ?? 0) \("分钟".localized())").foregroundColor(.gray).font(.system(size: 12))
            }
            HStack(){
                Text("费用").foregroundColor(.black).font(.system(size: 12))
                Spacer()
                Text("\(laos_point?.price ?? 0) kip").foregroundColor(.gray).font(.system(size: 12))
            }
            
        }
        .padding(.bottom,20)
        .padding(.horizontal,15)
        .padding(.vertical,15)
        .background(.white)
        .clipShape(RoundedRectangle(cornerRadius: 16)) // 先裁剪圆角
    }
    
    func distanceKM(distance : Double )-> String {
        let km = distance / 1000
        let formatted = String(format: "%.3f", km)
          return formatted
    }
   
}
